﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Interactivity;
using System.Windows.Input;
using BaseTypesLib;
using BBInterfaceNET.Designer.ViewModels;
using System.Diagnostics;
using BaseTypesLib.Model;
using System.Windows.Media;

namespace BBInterfaceNET.Designer.Behaviors
{
    public class ClickSelectBehavior:Behavior<FrameworkElement>
    {
        protected override void OnAttached()
        {
            base.OnAttached();
            FileDesignerViewModel vm = AssociatedObject.DataContext as FileDesignerViewModel;
            Debug.WriteLine("Attached for " + vm);
            AssociatedObject.MouseLeftButtonDown += AssociatedObject_MouseLeftButtonDown;
        }

        void AssociatedObject_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            FileDesignerViewModel vm = AssociatedObject.DataContext as FileDesignerViewModel;
            if (vm == null) return;

            FrameworkElement orig = e.OriginalSource as FrameworkElement;
            if (orig == null)
            {
                vm.ClearSelection();
                return;
            }
            Field field = orig.DataContext as Field;
            while(field==null && orig!=null)
            {
                orig = VisualTreeHelper.GetParent(orig) as FrameworkElement;
                if (orig == null) break;
                field = orig.DataContext as Field;
            }
            if (field == null)
            {
                vm.ClearSelection();
                return;
            }
            vm.SelectionChanged(field);
            vm.InvalidateCommands();
            e.Handled = true;
        }
        protected override void OnDetaching()
        {
            base.OnDetaching();
            FileDesignerViewModel vm = AssociatedObject.DataContext as FileDesignerViewModel;
            Debug.WriteLine("Detaching for " + vm.FilePath);
            AssociatedObject.MouseLeftButtonDown -= AssociatedObject_MouseLeftButtonDown;
        }
    }
}
